<template>
	<view class="container" :style="pageHeight">
		<view class="box-1">
			<scroll-view 
				scroll-y 
				refresher-background="transparent"
				style="height: 100%;" 
				@refresherrefresh="refresherrefresh"
				:refresher-enabled="true"
				:scroll-with-animation="false"
				:refresher-triggered="scrollView.refresherTriggered"
				:scroll-into-view="scrollView.intoView"
			>
				<view class="talk-list">
					<view v-if="talkList.length === 0" class="empty-chat">
						<text>还没有聊天记录，开始聊天吧</text>
					</view>
					<view 
						v-for="(item) in talkList" 
						:key="item.id" 
						:id="'msg-'+item.id"
					>
						<view class="item flex-col" :class=" item.type == 1 ? 'push':'pull' ">
							<image :src="item.pic" mode="aspectFill" class="pic"></image>
							<view class="content">
								<template v-if="item.contentType === 'image'">
									<image :src="item.content" mode="widthFix" style="width: 400rpx;"></image>
								</template>
								<template v-else>
									{{item.content}}
								</template>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="box-2">
			<view class="flex-col">
				<view style="margin-right: 20rpx;">
					<uni-icons type="image" size="24" color="#42b983" @tap="handleImageClick"></uni-icons>
				</view>
				<view class="flex-grow">
					<input type="text" class="content" v-model="content" placeholder="请输入聊天内容" placeholder-style="color:#DDD;" :cursor-spacing="6">
				</view>
				<button class="send" @tap="handleSendClick">发送</button>
			</view>
		</view>
	</view>
</template>

<script>
import request from '../../utils/request.js';
import userStatusService from '../../utils/userStatusService.js';
export default {
	data() {
		return {
			// 滚动容器
			scrollView:{
				refresherTriggered:false,
				intoView:"",
			safeAreaHeight:0
			},
			// 聊天列表数据
			talkList:[],
			// 请求参数
			ajax:{
				rows:20,    //每页数量
				page:1,  //页码
				flag:true,   // 请求开关
			},
			// 发送内容
			content:'',
			// 当前聊天好友信息
			currentFriend: null,
			// 消息监听器引用
			messageListener: null,
			// 当前会话ID
			conversationId: '',
			// 用户自己的信息
			currentUser: {
				id: '',
				avatar: '/static/avater/avatar.jpeg'
			}
		}
	},
	computed:{
		// 页面高度
		pageHeight(){
			const safeAreaHeight = this.scrollView.safeAreaHeight;
			if(safeAreaHeight > 0){
				return `height: calc(${safeAreaHeight}px - var(--window-top));`
			}
			return "";
		}
	},
	onLoad(options) {
		console.log('聊天页面加载，参数:', options);
		
		// #ifdef H5
		this.scrollView.safeAreaHeight = uni.getSystemInfoSync().safeArea.height;
		// #endif
		
		// 解析从上一个页面传递的好友信息
		if (options.friendInfo) {
			try {
				this.currentFriend = JSON.parse(decodeURIComponent(options.friendInfo));
				console.log('当前聊天好友:', this.currentFriend);
				// 设置页面标题为好友名称
				uni.setNavigationBarTitle({
					title: this.currentFriend.name || this.currentFriend.username || '聊天'
				});
			} catch (e) {
				console.error('解析好友信息失败:', e);
				uni.showToast({
					title: '无法加载聊天信息',
					icon: 'none'
				});
			}
		}
		
		// 获取当前用户信息
		this.getCurrentUserInfo();
		
		// 初始化WebSocket连接
		this.initWebSocket();
	},
	onShow() {
		console.log('聊天页面显示');
		// 初始化消息监听
		this.initMessageListener();
		
		// 获取历史消息
		this.getMessage();
	},
	onUnload() {
		console.log('聊天页面卸载');
		// 清理消息监听
		if (this.messageListener) {
			uni.$off('newMessageReceived', this.messageListener);
			this.messageListener = null;
		}
	},
	methods: {
		// 获取当前用户信息
		getCurrentUserInfo() {
			try {
				// 从本地存储获取用户信息
				const userInfo = uni.getStorageSync('userInfo');
				if (userInfo) {
					const user = JSON.parse(userInfo);
					this.currentUser.id = user.id || '';
					this.currentUser.avatar = user.avatar || '/static/avater/avatar.jpeg';
				}
			} catch (e) {
				console.error('获取当前用户信息失败:', e);
			}
		},
		
		// 初始化WebSocket连接
		initWebSocket() {
			if (userStatusService) {
				// 确保WebSocket已连接
				if (!userStatusService.socket) {
					console.log('WebSocket未初始化，尝试初始化');
					userStatusService.initWebSocket();
				} else if (!userStatusService.isConnected) {
					console.log('WebSocket未连接，尝试重连');
					userStatusService.initWebSocket();
				} else {
					console.log('WebSocket已连接');
				}
			} else {
				console.error('userStatusService未加载');
			}
		},
		
		// 发送消息
		handleSendClick() {
			console.log( this.currentUser.id)
			if (!this.content.trim() || !this.currentFriend || !this.currentUser.id) {
				console.log(222)
				return;
			}
			
			console.log('发送消息:', this.content, '给:', this.currentFriend.name || this.currentFriend.username);
			
			// 创建新消息对象
			const newMessage = {
				id: Date.now(),
				type: 1, // 1表示自己发送的
				content: this.content,
				contentType: 'text',
				pic: this.currentUser.avatar,
				timestamp: new Date().getTime()
			};
			
			// 添加到消息列表
			this.talkList.push(newMessage);
			console.log('消息添加到本地列表');
			
			// 滚动到底部
			this.$nextTick(() => {
				this.scrollView.intoView = `msg-${newMessage.id}`;
			});
			
			// 调用后端API发送消息
			this.sendChatMessageToBackend(this.currentFriend.id, this.content);
			
			// 清空输入框
			this.content = '';
		},
		
		// 调用后端API发送消息
		async sendChatMessageToBackend(receiverId, content) {
			try {
				console.log('开始调用API发送消息:', { receiverId, content });
				const token = uni.getStorageSync('accessToken');
				console.log('当前token:', token ? '存在' : '不存在');
				
				const response = await request({
					url: '/messages/send',
					method: 'POST',
					data: {
						receiverId: receiverId,
						content: content,
						messageType: 'text'
					}
				});
				
				console.log('消息发送到服务器成功:', response);
				uni.showToast({
					title: '发送成功',
					icon: 'success',
					duration: 1000
				});
				
			} catch (error) {
				console.error('发送消息到服务器失败:', error);
				console.error('错误详情:', JSON.stringify(error));
				
				// 获取更详细的错误信息
				let errorMsg = '发送失败';
				if (error.statusCode === 401) {
					errorMsg = '认证失败，请重新登录';
					// 可以考虑跳转到登录页
				} else if (error.statusCode === 500) {
					errorMsg = '服务器内部错误';
				}
				
				uni.showToast({
					title: errorMsg,
					icon: 'none',
					duration: 1000
				});
			}
		},
		
		// 初始化消息监听
		initMessageListener() {
			console.log('初始化消息监听');
			// 先移除可能存在的监听器，防止重复监听
			if (this.messageListener) {
				uni.$off('newMessageReceived', this.messageListener);
			}
			
			this.messageListener = (message) => {
				console.log('收到新消息:', message);
				
				// 确保currentFriend已初始化
				if (!this.currentFriend) return;
				
				// 处理不同格式的消息
				let messageData = message;
				// 兼容不同的消息结构
				if (message.data) {
					messageData = message.data;
				}
				
				// 只处理与当前好友的聊天消息
				if (messageData.from === this.currentFriend.id) {
					// 添加收到的消息到列表
					const receivedMessage = {
						id: messageData.id || Date.now(),
						type: 0, // 0表示收到的
						content: messageData.content,
						contentType: messageData.message_type || 'text',
						pic: this.currentFriend.avatar || this.currentFriend.avatarUrl || '/static/avater/default.png',
						timestamp: messageData.created_at || Date.now()
					};
					this.talkList.push(receivedMessage);
					console.log('添加收到的消息到列表');
					
					// 滚动到底部
					this.$nextTick(() => {
						const lastMsg = this.talkList[this.talkList.length - 1];
						this.scrollView.intoView = `msg-${lastMsg.id}`;
					});
				}
			};
			
			// 监听全局消息事件
			uni.$on('newMessageReceived', this.messageListener);
		},
		
		// 下拉刷新
		refresherrefresh(e) {
			console.log('下拉刷新');
			this.getMessage();
			this.scrollView.refresherTriggered = true;
		},
		
		// 获取历史消息
		async getMessage() {
			if(!this.ajax.flag) {
				return;
			}
			
			// 如果有当前聊天好友，可以根据好友ID获取历史消息
			if (this.currentFriend && this.currentUser.id) {
				console.log('获取历史消息');
				try {
					// 确定会话ID（与后端保持一致的生成规则）
					this.conversationId = this.currentUser.id < this.currentFriend.id 
						? `${this.currentUser.id}_${this.currentFriend.id}` 
						: `${this.currentFriend.id}_${this.currentUser.id}`;
					
					// 调用后端API获取历史消息
					const response = await request.get(`/api/messages/conversation/${this.conversationId}`);
					
					if (response.data && response.data.data) {
						// 处理历史消息数据
						this.talkList = response.data.data.map(msg => ({
							id: msg.id,
							type: msg.sender_id === this.currentUser.id ? 1 : 0, // 1表示自己发送的
							content: msg.content,
							contentType: msg.message_type || 'text',
							pic: msg.sender_id === this.currentUser.id 
								? this.currentUser.avatar 
								: (this.currentFriend.avatar || this.currentFriend.avatarUrl || '/static/avater/default.png'),
							timestamp: new Date(msg.created_at).getTime()
						}));
						console.log('加载历史消息:', this.talkList);
					}
				} catch (error) {
					console.error('获取历史消息失败:', error);
					// 发生错误时使用模拟数据
					this.loadMockHistoryMessages();
				}
			}
			this.scrollView.refresherTriggered = false;
		},
		
		// 加载模拟历史消息
		loadMockHistoryMessages() {
			const mockHistoryMessages = [
				{
					id: 'hist1',
					type: 0, // 收到的
					content: '你好！',
					pic: this.currentFriend.avatar || this.currentFriend.avatarUrl || '/static/avater/default.png',
					timestamp: Date.now() - 3600000
				},
				{
					id: 'hist2',
					type: 1, // 发送的
					content: '你好，最近怎么样？',
					pic: this.currentUser.avatar,
					timestamp: Date.now() - 3500000
				}
			];
			this.talkList = mockHistoryMessages;
		},
		
		// 处理图片点击
		handleImageClick() {
			console.log('选择图片');
			// 实现选择图片功能
			uni.chooseImage({
				count: 1,
				success: async (res) => {
					const tempFilePath = res.tempFilePaths[0];
					console.log('选择图片成功:', tempFilePath);
					// 发送图片消息
					if (this.currentFriend) {
						try {
							// 上传图片到服务器
							const uploadResult = await this.uploadImage(tempFilePath);
							if (uploadResult.success && uploadResult.imageUrl) {
								// 创建图片消息对象
								const imageMessage = {
									id: Date.now(),
									type: 1,
									contentType: 'image',
									content: uploadResult.imageUrl,
									pic: this.currentUser.avatar,
									timestamp: Date.now()
								};
								
								// 添加到本地列表
								this.talkList.push(imageMessage);
								this.$nextTick(() => {
									this.scrollView.intoView = `msg-${imageMessage.id}`;
								});
								
								// 调用后端API发送图片消息
								await this.sendChatMessageToBackend(this.currentFriend.id, uploadResult.imageUrl);
								
								uni.showToast({
									title: '图片发送成功',
									icon: 'success'
								});
							} else {
								throw new Error('图片上传失败');
							}
						} catch (error) {
							console.error('图片消息发送失败:', error);
							uni.showToast({
								title: '图片发送失败',
								icon: 'none'
							});
						}
					}
				}, fail: (err) => {
					console.error('选择图片失败:', err);
				}
			});
		},
		
		// 上传图片
		uploadImage(filePath) {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: 'http://192.168.0.154:3000/api/upload',
					filePath: filePath,
					name: 'file',
					success: (uploadRes) => {
						try {
							const data = JSON.parse(uploadRes.data);
							if (data.success && data.data && data.data.url) {
								resolve({ success: true, imageUrl: data.data.url });
							} else {
								reject(new Error('上传失败: ' + (data.message || '未知错误')));
							}
						} catch (e) {
							reject(new Error('解析上传结果失败'));
						}
					},
					fail: (error) => {
						reject(error);
					}
				});
			});
		}
	}
}
</script>

<style lang="scss">	@import "../../lib/global.scss";
	page{
		background-color: #F3F3F3;
		font-size: 28rpx;
	}
	.container{
		height: calc(100vh - var(--window-top));
		display: flex;
		flex-direction: column;
		flex-wrap: nowrap;
		align-content: center;
		justify-content: space-between;
		align-items: stretch;
	}
	
	.empty-chat {
		padding: 100rpx 0;
		text-align: center;
		color: #999;
	}
	
	/* 加载数据提示 */
	.tips{
		position: fixed;
		left: 0;
		top:var(--window-top);
		width: 100%;
		z-index: 9;
		background-color: rgba(0,0,0,0.15);
		height: 72rpx;
		line-height: 72rpx;
		transform:translateY(-80rpx);
		transition: transform 0.3s ease-in-out 0s;
		
		&.show{
			transform:translateY(0);
		}
	}
	
	.box-1{
		width: 100%;
		height: 0;
		flex: 1 0 auto;
		box-sizing: content-box;
	}
	.box-2{
		height: auto;
		z-index: 2;
		border-top: #e5e5e5 solid 1px;
		box-sizing: content-box;
		background-color: #F3F3F3;
		
		/* 兼容iPhoneX */
		padding-bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		
		>view{
			padding: 0 20rpx;
			height: 100rpx;
		}
		
		.content{
			background-color: #fff;
			height: 64rpx;
			padding: 0 20rpx;
			border-radius: 32rpx;
			font-size: 28rpx;
		}
		
		.send{
			background-color: #42b983;
			color: #fff;
			height: 64rpx;
			margin-left: 20rpx;
			border-radius: 32rpx;
			padding: 0;
			width: 120rpx;
			line-height: 62rpx;
			
			&:active{
				background-color: #5fc496;
			}
		}
	}
	
	.talk-list{
		padding-bottom: 20rpx;
		display: flex;
		flex-direction: column-reverse;
		flex-wrap: nowrap;
		align-content: flex-start;
		justify-content: flex-end;
		align-items: stretch;
		
		// 添加弹性容器，让内容自动在顶部
		&::before{
			content: '.';
			display: inline;
			visibility: hidden;
			line-height: 0;
			font-size: 0;
			flex: 1 0 auto;
			height: 1px;
		}
		
		
		/* 消息项，基础类 */
		.item{
			padding: 20rpx 20rpx 0 20rpx;
			align-items:flex-start;
			align-content:flex-start;
			color: #333;
			
			.pic{
				width: 92rpx;
				height: 92rpx;
				border-radius: 50%;
				border: #fff solid 1px;
			}
			
			.content{
				padding: 20rpx;
				border-radius: 4px;
				max-width: 500rpx;
				word-break: break-all;
				line-height: 52rpx;
				position: relative;
			}
			
			/* 收到的消息 */
			&.pull{
				.content{
					margin-left: 32rpx;
					background-color: #fff;
					
					&::after{
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-right: 20rpx solid #fff;
						position: absolute;
						top: 30rpx;
						left: -18rpx;
					}
				}
			}
			
			/* 发出的消息 */
			&.push{
				/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
				flex-direction: row-reverse;
				
				.content{
					margin-right: 32rpx;
					background-color: #a0e959;
					
					&::after{
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-left: 20rpx solid #a0e959;
						position: absolute;
						top: 30rpx;
						right: -18rpx;
					}
				}
			}
		}
	}
</style>
<template>
	<view class="content">
		<view class="content-box" @touchstart="touchstart" id="content-box" :class="{'content-showfn':showFunBtn}">
			<!-- 背景图- 定位方式 -->
			<image class="content-box-bg" :src="_user_info.chatBgImg" :style="{ height: imgHeight }"></image>
			<view class="content-box-loading" v-if="!loading"><u-loading mode="flower"></u-loading></view>
			<view class="message" v-for="(item, index) in messageList" :key="index" :id="`msg-${item.hasBeenSentId}`">
				<view class="message-item " :class="item.isItMe ? 'right' : 'left'">
					<image class="img" :src="item.fromUserHeadImg" mode="" @tap="linkToBusinessCard(item.fromUserId)"></image>
					<!-- contentType = 1 文本 -->
					<view class="content" v-if="item.contentType == 1">{{ item.content }}</view>
					<!-- contentType = 2 语音 -->
					<view
						class="content contentType2"
						:class="[{ 'content-type-right': item.isItMe }]"
						v-if="item.contentType == 2"
						@tap="handleAudio(item)"
						hover-class="contentType2-hover-class"
						:style="{width:`${130+(item.contentDuration*2)}rpx`}"
					>
						<view
							class="voice_icon"
							:class="[
								{ voice_icon_right: item.isItMe },
								{ voice_icon_left: !item.isItMe },
								{ voice_icon_right_an: item.anmitionPlay && item.isItMe },
								{ voice_icon_left_an: item.anmitionPlay && !item.isItMe }
							]"
						></view>
						<view class="">{{ item.contentDuration }}''</view>
					</view>
					<!-- contentType = 3 图片 -->
					<view 
						class="content contentType3" 	
						v-if="item.contentType == 3"
						@tap="viewImg([item.content])"
					>
						<image :src="item.content" class="img" mode="widthFix"></image>
					</view>
				</view>
			</view> 
		</view>
		
		<!-- 底部聊天输入框 -->
		<view class="input-box" :class="{ 'input-box-mpInputMargin': mpInputMargin }">
			<view class="input-box-flex">
				<!-- #ifndef H5 -->
				<image v-if="chatType === 'voice'" class="icon_img" :src="require('@/static/voice.png')"  @click="switchChatType('keyboard')"></image>
				<image v-if="chatType === 'keyboard'" class="icon_img" :src="require('@/static/keyboard.png')"  @click="switchChatType('voice')"></image>
				<!-- #endif -->
				<view class="input-box-flex-grow"> 
					<input
						v-if="chatType === 'voice'"
						type="text"
						class="content"
						id="input"
						v-model="formData.content"
						:hold-keyboard="true"
						:confirm-type="'send'"
						:confirm-hold="true"
						placeholder-style="color:#DDDDDD;"
						:cursor-spacing="10"
						@confirm="sendMsg(null)"
					/>
					<view
						class="voice_title"
						v-if="chatType === 'keyboard'"
						:style="{ background: recording ? '#c7c6c6' : '#FFFFFF' }"
						@touchstart.stop.prevent="startVoice"
						@touchmove.stop.prevent="moveVoice"
						@touchend.stop="endVoice"
						@touchcancel.stop="cancelVoice"
					>
						{{ voiceTitle }}
					</view>
				</view>
				
				<!-- 功能性按钮 -->
				<image class=" icon_btn_add" :src="require('@/static/add.png')" @tap="switchFun"></image>
				
				<!-- #ifdef H5 --> 
				<button class="btn" type="primary" size="mini" @touchend.prevent="sendMsg(null)">发送</button>
				<!-- #endif -->
			</view>
			
			<view class="fun-box" :class="{'show-fun-box':showFunBtn}">
				<u-grid :col="4"  hover-class="contentType2-hover-class" :border="false" @click="clickGrid">
					<u-grid-item v-for="(item, index) in funList" :index="index" :key="index" bg-color="#eaeaea">
						<u-icon :name="item.icon" :size="52"></u-icon>
						<view class="grid-text">{{ item.title }}</view>
					</u-grid-item>
				</u-grid>
			</view>

		</view>
		
		<!-- //语音动画 -->
		<view class="voice_an"  v-if="recording">
			<view class="voice_an_icon">
				<view id="one" class="wave"></view>
				<view id="two" class="wave"></view>
				<view id="three" class="wave"></view>
				<view id="four" class="wave"></view>
				<view id="five" class="wave"></view>
				<view id="six" class="wave"></view>
				<view id="seven" class="wave"></view>
			</view>
			<view class="text">{{voiceIconText}}</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			fromUserInfo: {},
			formData: {
				content: '',
				limit: 15,
				index: 1
			},
			messageList: [],
			loading: true, //标识是否正在获取数据
			imgHeight: '1000px',
			mpInputMargin: false, //适配微信小程序 底部输入框高度被顶起的问题
			chatType:"voice",  // 图标类型 'voice'语音 'keyboard'键盘
			voiceTitle: '按住 说话',
			Recorder: uni.getRecorderManager(),
			Audio: uni.createInnerAudioContext(),
			recording: false, //标识是否正在录音
			isStopVoice: false, //加锁 防止点击过快引起的当录音正在准备(还没有开始录音)的时候,却调用了stop方法但并不能阻止录音的问题
			voiceInterval:null,
			voiceTime:0, //总共录音时长
			canSend:true, //是否可以发送
			PointY:0, //坐标位置
			voiceIconText:"正在录音...",
			showFunBtn:false, //是否展示功能型按钮
			AudioExam:null, //正在播放音频的实例
			funList: [
				{ icon:"photo-fill",title:"照片",uploadType:["album"] },
				{ icon:"camera-fill",title:"拍摄",uploadType:["camera"] },
			],
		};
	},
	methods: {
		//拼接消息 处理滚动
		async joinData() {
			if (!this.loading) {
				//如果没有获取数据 即loading为false时，return 避免用户重复上拉触发加载
				return;
			}
			this.loading = false;
			const data = await this.getMessageData();
			//获取节点信息
			const { index } = this.formData;
			const sel = `#msg-${index > 1 ? this.messageList[0].hasBeenSentId : data[data.length - 1].hasBeenSentId}`;
			this.messageList = [...data, ...this.messageList];
			//填充数据后，视图会自动滚动到最上面一层然后瞬间再跳回bindScroll的指定位置 ---体验不是很好，后期优化
			this.$nextTick(() => {
				this.bindScroll(sel);
				//如果还有数据
				if (this.formData.limit >= data.length) {
					this.formData.index++;
					setTimeout(() => {
						this.loading = true;
					}, 200);
				}
			});
		},
		//处理滚动
		bindScroll(sel, duration = 0) {
			const query = uni.createSelectorQuery().in(this);
			query
				.select(sel)
				.boundingClientRect(data => {
					uni.pageScrollTo({
						scrollTop: data && data.top - 40,
						duration
					});
				})
				.exec();
		},
		//获取消息
		getMessageData() {
			let getData = () => {
				let arr = [];
				let startIndex = (this.formData.index - 1) * this.formData.limit;
				let endIndex = startIndex + this.formData.limit;
				for (let i = startIndex; i < endIndex; i++) {
					const isItMe = Math.random() > 0.5 ? true : false;
					arr.unshift({
						hasBeenSentId: i, //已发送过去消息的id
						content: `很高兴认识你，这是第${i + 1}条消息。`,
						fromUserHeadImg: isItMe ? this._user_info.headImg : this.fromUserInfo.fromUserHeadImg, //用户头像
						fromUserId: isItMe ? this._user_info.id : this.fromUserInfo.fromUserId,
						isItMe, //true此条信息是我发送的 false别人发送的
						createTime: Date.now(),
						contentType: 1, // 1文字文本 2语音
						anmitionPlay: false //标识音频是否在播放
					});
				}
				return arr;
			};
			return new Promise((resolve, reject) => {
				const data = getData();
				setTimeout(() => {
					resolve(data);
				}, 500);
			});
		},
		//切换语音或者键盘方式
		switchChatType(type) {
			this.chatType = type;
			this.showFunBtn =false;
		},
		//切换功能性按钮
		switchFun(){
			this.chatType = 'keyboard'
			this.showFunBtn = !this.showFunBtn;
			uni.hideKeyboard()
		},
		//发送消息
		sendMsg(data) {
			const params = {
				hasBeenSentId: Date.now(), //已发送过去消息的id
				content: this.formData.content,
				fromUserHeadImg: this._user_info.headImg, //用户头像
				fromUserId: this._user_info.id,
				isItMe: true, //true此条信息是我发送的  false别人发送的
				createTime: Date.now(),
				contentType: 1
			};

			if (data) {
				if(data.contentType == 2){
					//说明是发送语音
					params.content = data.content;
					params.contentType = data.contentType;
					params.contentDuration = data.contentDuration;
					params.anmitionPlay = false;
				}else if(data.contentType == 3){
					//发送图片
					params.content = data.content;
					params.contentType = data.contentType;
				}
			} else if (!this.$u.trim(this.formData.content)) {
				//验证输入框书否为空字符传
				return;
			}

			this.messageList.push(params);

			this.$nextTick(() => {
				this.formData.content = '';
				// #ifdef MP-WEIXIN
					if(params.contentType == 1){
						uni.pageScrollTo({
							scrollTop: 99999,
							duration: 0, //小程序如果有滚动效果 input的焦点也会随着页面滚动...
						});
					}else{
						setTimeout(()=>{
							uni.pageScrollTo({
								scrollTop: 99999,
								duration: 0, //小程序如果有滚动效果 input的焦点也会随着页面滚动...
							});
						},150)
					}
				// #endif
					
				// #ifndef MP-WEIXIN
					uni.pageScrollTo({
						scrollTop: 99999,
						duration: 100
					});
				// #endif
				
				if(this.showFunBtn){
					this.showFunBtn = false;
				}
				
				// #ifdef MP-WEIXIN 
				if (params.contentType == 1) {
					this.mpInputMargin = true;
				} 
				// #endif
				//h5浏览器并没有很好的办法控制键盘一直处于唤起状态 而且会有样式性的问题
				// #ifdef H5
				uni.hideKeyboard();
				// #endif
			});
		},
		//用户触摸屏幕的时候隐藏键盘
		touchstart() {
			uni.hideKeyboard();
		},
		// userid 用户id
		linkToBusinessCard(userId) {
			this.$u.route({
				url: 'pages/businessCard/businessCard',
				params: {
					userId
				}
			});
		},
		//准备开始录音
		startVoice(e) {
			if(!this.Audio.paused){
				//如果音频正在播放 先暂停。
				this.stopAudio(this.AudioExam)
			}
			this.recording = true;
			this.isStopVoice = false;
			this.canSend = true;
			this.voiceIconText = "正在录音..."
			this.PointY = e.touches[0].clientY;
			this.Recorder.start({
				format: 'mp3'
			});
		},
		//录音已经开始
		beginVoice(){
			if (this.isStopVoice) {
				this.Recorder.stop();
				return;
			}
			this.voiceTitle = '松开 结束'
			this.voiceInterval =  setInterval(()=>{
				this.voiceTime ++;
			},1000)
		},
		//move 正在录音中
		moveVoice(e){
			const PointY = e.touches[0].clientY
			const slideY = this.PointY - PointY;
			if(slideY > uni.upx2px(120)){
				this.canSend = false;
				this.voiceIconText = '松开手指 取消发送 '
			}else if(slideY > uni.upx2px(60)){
				this.canSend = true;
				this.voiceIconText = '手指上滑 取消发送 '
			}else{
				this.voiceIconText = '正在录音... '
			}
		},
		//结束录音
		endVoice() {
			this.isStopVoice = true; //加锁 确保已经结束录音并不会录制
			this.Recorder.stop();
			this.voiceTitle = '按住 说话'
		},
		//录音被打断
		cancelVoice(e){
			this.voiceTime = 0;
			this.voiceTitle = '按住 说话';
			this.canSend = false;
			this.Recorder.stop();
		},
		//处理录音文件
		handleRecorder({ tempFilePath,duration }) {
			let contentDuration;
			// #ifdef MP-WEIXIN
			this.voiceTime = 0;
			if (duration < 600) {
				this.voiceIconText="说话时间过短";
				setTimeout(()=>{
					this.recording = false;
				},200)
				return;
			} 
			contentDuration = duration/1000;
			// #endif
			
			// #ifdef APP-PLUS
			contentDuration = this.voiceTime +1;
			this.voiceTime = 0;
			if(contentDuration <= 0) {
				this.voiceIconText="说话时间过短";
				setTimeout(()=>{
					this.recording = false;
				},200)
				return;
			};
			// #endif
			
			this.recording = false;
			const params = {
				contentType: 2,
				content: tempFilePath,
				contentDuration: Math.ceil(contentDuration)
			};
			this.canSend && this.sendMsg(params);
		},
		//控制播放还是暂停音频文件
		handleAudio(item) {
			this.AudioExam = item;
			this.Audio.paused ? this.playAudio(item) : this.stopAudio(item);
		},
		//播放音频
		playAudio(item) {
			this.Audio.src = item.content;
			this.Audio.hasBeenSentId = item.hasBeenSentId;
			this.Audio.play();
			item.anmitionPlay = true;
		},
		//停止音频
		stopAudio(item) {
			item.anmitionPlay = false;
			this.Audio.src = '';
			this.Audio.stop();
		},
		//关闭动画
		closeAnmition() {
			const hasBeenSentId = this.Audio.hasBeenSentId;
			const item = this.messageList.find(it => it.hasBeenSentId == hasBeenSentId);
			item.anmitionPlay = false;
		},
		//点击宫格时触发
		clickGrid(index){
			if(index == 0){
				this.chooseImage(['album'])
			}else if(index == 1){
				this.chooseImage(['camera'])
			}
		},
		//发送图片
		chooseImage(sourceType){
			uni.chooseImage({
				sourceType,
				sizeType:['compressed'], 
				success:res=>{ 
					this.showFunBtn = false;
					for(let i = 0;i<res.tempFilePaths.length;i++){
						const params = {
							contentType: 3,
							content: res.tempFilePaths[i],
						};
						this.sendMsg(params)
					}
				}
			})
		},
		//查看大图
		viewImg(imgList){
			uni.previewImage({
				urls: imgList,
				// #ifndef MP-WEIXIN
				indicator: 'number'
				// #endif
			});
		},
	},
	onPageScroll(e) {
		if (e.scrollTop < 50) {
			this.joinData();
		}
	},
	onNavigationBarButtonTap({ index }) {
		if (index == 0) {
			//用户详情 设置
		} else if (index == 1) {
			//返回按钮
			this.$u.route({
				type: 'switchTab',
				url: 'pages/home/home'
			});
		}
	},
	//返回按钮事件
	onBackPress(e) {
		//以下内容对h5不生效
		//--所以如果用浏览器自带的返回按钮进行返回的时候页面不会重定向 正在寻找合适的解决方案
		this.$u.route({
			type: 'switchTab',
			url: 'pages/home/home'
		});
		return true;
	},
	onLoad(info) {
		// { messageId,fromUserName,fromUserHeadImg } = info
		const userInfo = this.firendList.filter(item => item.userId == info.fromUserId)[0];
		this.fromUserInfo = {
			fromUserName: userInfo.userName,
			fromUserHeadImg: userInfo.headImg,
			fromUserId: userInfo.userId,
			messageId: info.messageId
		};

		//录音开始事件
		this.Recorder.onStart(e => {
			
			this.beginVoice();
		});
		//录音结束事件
		this.Recorder.onStop(res => {
			clearInterval(this.voiceInterval);
			this.handleRecorder(res);
		});

		//音频停止事件
		this.Audio.onStop(e => {
			this.closeAnmition();
		});

		//音频播放结束事件
		this.Audio.onEnded(e => {
			this.closeAnmition();
		});
	},
	onReady() {
		//自定义返回按钮 因为原生的返回按钮不可阻止默认事件
		// #ifdef H5
		const icon = document.getElementsByClassName('uni-page-head-btn')[0];
		icon.style.display = 'none';
		// #endif

		uni.setNavigationBarTitle({
			title: this.fromUserInfo.fromUserName
		});
		this.joinData();
		uni.getSystemInfo({
			success: res => {
				this.imgHeight = res.windowHeight + 'px';
			}
		});
		
		uni.onKeyboardHeightChange(res => {
			if (res.height == 0) {
				// #ifdef MP-WEIXIN
				this.mpInputMargin = false;
				// #endif
			}else{
				this.showFunBtn = false;
			}
		});
	}
};
</script>

<style lang="scss" scoped>
 @import './index.scss'
</style>
